package com.yihu.cms.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yihu.cms.service.WexinMsgByGroupService;
import com.yihu.cms.util.HttpUtils;
import com.yihu.cms.util.Osslog;
import com.yihu.cms.util.PropertiesUtil;
import com.yihu.web.bean.GroupBuy;
import com.yihu.web.bean.OrdersList;
import com.yihu.web.bean.Seckill;
import com.yihu.web.bean.SeckillResult;
import com.yihu.web.bean.order.Express;
import com.yihu.web.bean.order.Order;
import com.yihu.web.bean.order.Product;
import com.yihu.web.bean.vo.OrderQuery;
import com.yihu.web.constats.DSConstants;
import com.yihu.web.constats.ResponseVO;
import com.yihu.web.constats.ResultVO;
import com.yihu.web.utils.FormatDateTime;
import com.yihu.web.utils.InfoHelp;
import com.yihu.yihuds.service.GroupBuyService;
import com.yihu.yihuds.service.OrderService;
import com.yihu.yihuds.service.YihuUserService;

/***
 * 订单管理
 * 
 * @author Aaron
 *
 */
@Controller
public class OrderController extends BaseController {
	@Autowired
	private HttpServletRequest request;
	OrderService service = new OrderService();
	GroupBuyService gService = new GroupBuyService();
	YihuUserService userService = new YihuUserService();

	/***
	 * if cutAndTeam = true,去除砍价拼团订单
	 * @param pQuery
	 * @return
	 */
	@RequestMapping(value = "/order/list", method = RequestMethod.GET)
	public @ResponseBody Object getOrders(OrderQuery pQuery) {
		return service.findByPage(pQuery);
	}
	
	@RequestMapping(value = "/order/count", method = RequestMethod.GET)
	public @ResponseBody Object getOrderCount(OrderQuery pQuery) {
		return service.getOrderCount(pQuery);
	}
	
	@RequestMapping(value = "/order/delete/{orderNo}", method = RequestMethod.DELETE)
	public @ResponseBody Object delete(@PathVariable("orderNo") String orderNo) {
		System.out.println(orderNo);
		Order order = new Order();
		order.setOrderNo(orderNo);
		order = service.delete(order);
		String reqUrl = PropertiesUtil.getInstance().getProperty("teamurl")+"deletesuccess?id="+order.getSpreadId();
		String result = "";
		try {
			result = HttpUtils.sendGet(reqUrl);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping(value = "/order/{id}", method = RequestMethod.GET)
	public @ResponseBody Object getOrder(@PathVariable("id") String id) {
		return service.getById(id);
	}

	@RequestMapping(value = "/order", method = RequestMethod.GET)
	public @ResponseBody Object getOrder(Order order) {
		Osslog.debug("getOrder: "+order);
		return service.getOrder(order);
	}

	// add order
	@RequestMapping(value = "/order", method = RequestMethod.POST)
	public @ResponseBody Object addOrder(@RequestBody Order order) {
		Osslog.debug("cms.addOrder: " + order);
		if (InfoHelp.isBlank(order.getOrderNo())) {
			String orderNo = FormatDateTime.toOrderNumber(new Date()); // 系统订单号
			order.setOrderNo(orderNo);
		}
		if (order.getType() == DSConstants.ORDER_TYPE_SECKILL) {
			String url = PropertiesUtil.getInstance().getProperty("seckillurl");
			try {
				if (order.getProducts().get(0) != null) {
					Product p = order.getProducts().get(0);
					url = url + p.getId() + "/detail";
					String result = HttpUtils.sendGet(url);
					SeckillResult skr = JSON.parseObject(result, SeckillResult.class);
					Osslog.debug("cms.addOrder.seckill: " + skr.getData());
					Seckill sk = skr.getData();
					p.setCount(1);
					p.setName(sk.getName());
					p.setIcon(sk.getIcon());
					p.setPrice(sk.getKillPrice().doubleValue());
					order.setTitle(sk.getName());
					order.setTotalFee(sk.getKillPrice().doubleValue());
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else if (order.getType() == DSConstants.ORDER_TYPE_GROUPBUY) {
			try {
				if (order.getProducts().get(0) != null) {
					Product p = order.getProducts().get(0);
					String groupId = p.getId();
					GroupBuy group = (GroupBuy) gService.getById(groupId);
					if (group.getBookmoq() >= group.getMoq()) {
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("result", 1);
						map.put("message", "this group not enough quantity");
						map.put("code", 2001);
						return map;
					}
					p.setName(group.getName());
					p.setIcon(group.getIcon());
					p.setPrice(group.getGroupPrice());
					order.setTitle(group.getName());
					order.setTotalFee(group.getGroupPrice() * p.getCount());
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else if (order.getType() == DSConstants.ORDER_TYPE_AUCTION) {
			String url = PropertiesUtil.getInstance().getProperty("auctionurl");
			try {
				if (order.getProducts().get(0) != null) {
					Product p = order.getProducts().get(0);
					url = url + p.getId();
					Osslog.debug("cms.addOrder.Auction.url: " + url);
					String result = HttpUtils.sendGet(url);
					Osslog.debug("cms.addOrder.Auction.result: " + result);
					JSONObject jo = JSON.parseObject(result);
					//AuctionProduct skr = JSON.parseObject(result, AuctionProduct.class);

					p.setCount(1);
					p.setName(jo.getString("name"));
					p.setIcon(jo.getString("icon"));
					p.setPrice(jo.getBigDecimal("maxPrice").doubleValue());
					order.setTitle(p.getName());
					order.setTotalFee(p.getPrice());
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else if (order.getType() == DSConstants.ORDER_TYPE_RECHARGE) {
			Osslog.debug("cms.addOrder.rechargeAccount ");
			if(order.getTotalFee()<=0){
				ResultVO vo = new ResultVO();
				vo.setResult(DSConstants.RESULT_CODE_FAIL);
				vo.setMessage("the totalFee is "+order.getTotalFee());
				return vo;
			}
		}else if(order.getType() == DSConstants.ORDER_TYPE_FIRST){
			String url1 = PropertiesUtil.getInstance().getProperty("firsturl");
			try {
				if (order.getProducts().get(0) != null) {
					double totalFee = 0;
					for(Product p:order.getProducts()){
						if(StringUtils.isBlank(p.getId()))
							continue;
						String url = url1 +"get/"+ p.getId();
						Osslog.debug("cms.addOrder.firsturl.url: " + url);
						String result = HttpUtils.sendGet(url);
						Osslog.debug("cms.addOrder.firsturl.result: " + result);
						JSONObject jo = JSON.parseObject(result);
						p.setCount(1);
						p.setName(jo.getString("name"));
						p.setIcon(jo.getString("icon"));
						p.setPrice(jo.getBigDecimal("buttomFee").doubleValue());
						totalFee += p.getPrice();
						
					}
					StringBuffer sb = new StringBuffer();
					sb.append(order.getProducts().get(0).getName());
					if(order.getProducts().size()>1){
						sb.append("等"+order.getProducts().size()+"件商品");
					}
					order.setTitle(sb.toString());
					order.setTotalFee(totalFee);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else if(order.getType() == DSConstants.ORDER_TYPE_TEAM){
			String url = PropertiesUtil.getInstance().getProperty("teamurl");
			try {
				if (order.getProducts().get(0) != null) {
					Product p = order.getProducts().get(0);
					String teamOrderId = p.getId();
					order.setSpreadId(teamOrderId);
					String geturl = url +"getinfo/"+ p.getId();
					Osslog.debug("cms.addOrder.team.url: " + geturl);
					String result = HttpUtils.sendGet(geturl);
					Osslog.debug("cms.addOrder.team.result: " + result);
					JSONObject jo = JSON.parseObject(result);
					String fieldId = jo.getString("fieldId");
					p.setCount(1);
					p.setName(jo.getString("name"));
					p.setIcon(jo.getString("icon"));
					p.setPrice(jo.getBigDecimal("teamFee").doubleValue());
					p.setId(fieldId);
					order.setTitle(p.getName());
					order.setTotalFee(p.getPrice());
					
					String orderUrl = url+"createsuccess?id="+teamOrderId;
					result = HttpUtils.sendGet(orderUrl);
					Osslog.debug("cms.addteamOrder.order.result: " + result);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		else if(order.getType() == DSConstants.ORDER_TYPE_CUT){
			String url = PropertiesUtil.getInstance().getProperty("cuturl");
			try {
				if (order.getProducts().get(0) != null) {
					Product p = order.getProducts().get(0);
					String cutOrderId = p.getId();
					order.setSpreadId(cutOrderId);
					String getUrl = url +"get/"+ p.getId();
					Osslog.debug("cms.addOrder.get.url: " + getUrl);
					String result = HttpUtils.sendGet(getUrl);
					Osslog.debug("cms.addOrder.get.result: " + result);
					JSONObject jo = JSON.parseObject(result);
					Long stock = jo.getLong("stock");
					Osslog.debug("cms.addOrder.get.stock: " + stock);
					if(stock!=null){
						if(stock.longValue()<=0){
							ResponseVO vo = new ResponseVO();
							vo.setResult(DSConstants.RESULT_CODE_FAIL);
							vo.setCode(100001);
							vo.setMessage("the product is sold out.");
							return vo;
						}
					}
					String fieldId = jo.getString("fieldId");
					p.setCount(1);
					p.setName(jo.getString("name"));
					p.setIcon(jo.getString("icon"));
					p.setPrice(jo.getBigDecimal("dealFee").doubleValue());
					p.setId(fieldId);
					order.setTitle(p.getName());
					order.setTotalFee(p.getPrice());
					String orderUrl = url+"createsuccess?id="+cutOrderId;
					result = HttpUtils.sendGet(orderUrl);
					Osslog.debug("cms.addcutOrder.order.result: " + result);
					
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}else if(order.getType()==DSConstants.ORDER_TYPE_TEAM_PAY){//拼团直接支付

			String url1 = PropertiesUtil.getInstance().getProperty("firsturl");
			try {
				if (order.getProducts().get(0) != null) {
					Product p = order.getProducts().get(0);	
					String url = url1 +"get/"+ p.getId();
					Osslog.debug("cms.addOrder.teamPayturl.url: " + url);
					String result = HttpUtils.sendGet(url);
					Osslog.debug("cms.addOrder.teamPayturl.result: " + result);
					JSONObject jo = JSON.parseObject(result);
					p.setCount(1);
					p.setName(jo.getString("name"));
					p.setIcon(jo.getString("icon"));
					p.setPrice(jo.getBigDecimal("fieldPrice").doubleValue());									
					order.setTitle(p.getName());
					order.setTotalFee(p.getPrice());
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		Object o = service.addOrder(order);
		Osslog.debug("cms.result: " + o);
		return o;
	}

	@RequestMapping(value = "/order/cancel", method = RequestMethod.POST)
	public @ResponseBody Object cancelOrder(@RequestBody Order order) {
		Osslog.debug("cms.cancelOrder：" + order);
		order.setStatus(DSConstants.ORDER_STATE_CANCEL);
		return service.cancelOrder(order);
	}
	
	@RequestMapping(value = "/order/batchcancel", method = RequestMethod.POST)
	public @ResponseBody Object batchcancelOrder(@RequestBody OrdersList ordersList) {
		Osslog.debug("cms.cancelOrder：" + ordersList);
		return service.batchCancelOrder(ordersList);
	}
	/***
	 * 后台调用完成订单
	 * @param order
	 * @return
	 */
	@RequestMapping(value = "/order/finish", method = RequestMethod.POST)
	public @ResponseBody Object finishOrder(@RequestBody Order order) {
		Osslog.debug("cms.finishOrder：" + order);
		order.setStatus(DSConstants.ORDER_STATE_RECEIVED);
		String finishUrl = PropertiesUtil.getInstance().getProperty("wxserviceurl") + "/orderfinish";
		try {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("url", "/#/order/"+order.getOrderNo());
			param.put("orderNo", order.getOrderNo());
			param.put("name", order.getTitle());
			param.put("date", FormatDateTime.toShortTimeString3(new Date()));
			param.put("openid", order.getOpenid());
			HttpUtils.sendPostJson(finishUrl, JSON.toJSONString(param));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return service.changeState(order);
	}

	@RequestMapping(value = "/order/refunds", method = RequestMethod.GET)
	public @ResponseBody Object refundsOrders(){
		return refundOrders();
	}

	private Object refundOrders() {
		List<Order> orders = service.refundOrders(48);
		List<ResultVO> vos = new ArrayList<ResultVO>();
		for(Order order:orders){
			String refundUrl = PropertiesUtil.getInstance().getProperty("wxserviceurl") + "/wx/refund";
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("orderNo", order.getOrderNo());
			param.put("openid", order.getOpenid());
			ResultVO vo = new ResultVO();
			JSONObject jobject = null;
			try {
				String result = HttpUtils.sendPostJson(refundUrl, JSON.toJSONString(param));
				jobject = JSONObject.parseObject(result);
				if(jobject.getInteger("result")==1){
					order.setStatus(DSConstants.ORDER_STATE_REFUND_FAIL);
					ResultVO v = (ResultVO) service.changeState(order);
					if(v.getResult()==1){
						vo.setMessage("Successful refunds, failure to update the order state");
					}
					vo.setResult(DSConstants.RESULT_CODE_FAIL);
					vo.setMessage(jobject.getString("err_code_des"));
					//退款失败发送 
					refundFailNotice(order);
				}
				
			} catch (Exception e) {
				vo.setResult(DSConstants.RESULT_CODE_FAIL);
				vo.setMessage(jobject.getString("err_code_des"));;
			} 
			vos.add(vo);
		}
		return vos;
	}

	private void refundFailNotice(Order o) {
		String result;
		String reqUrl = PropertiesUtil.getInstance().getProperty("wxserviceurl") + "/refund/sys";
		Map<String,Object> failParam = new HashMap<String,Object>();
		try {
			failParam.put("orderNo", o.getOrderNo());
			failParam.put("totalFee", o.getTotalFee());
			failParam.put("reason", "用户退款失败");
			failParam.put("openids", WexinMsgByGroupService.getCustomerService());	
			failParam.put("first", "有用户申请的退款失败，请及时在微信商户充值，然后在cms后台手动完成退款");
			result = HttpUtils.sendPostJson(reqUrl, JSON.toJSONString(failParam));
			Osslog.debug("refund.sys.result: "+result);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value = "/order/batchcancel", method = RequestMethod.GET)
	public @ResponseBody Object batchCancelOrder() {
		Osslog.debug("cms.batchCancelOrder: ");
		int hour = 24;//大概24个小时未支付，就取消订单
		List<Order> orders = service.batchCancelOrder(hour);
		Osslog.debug("cms.batchCancelOrder.result: "+orders);
		String reqUrl = PropertiesUtil.getInstance().getProperty("teamurl");
		reqUrl=reqUrl+"batchcancel";
		String cuturl = PropertiesUtil.getInstance().getProperty("cuturl")+"batchcancel";
		try {
			HttpUtils.sendGet(reqUrl);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			HttpUtils.sendGet(cuturl);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//自动退款
		refundOrders();
		
		
		return orders;
	}

	/***
	 * 订单更新
	 * 
	 * @param order
	 * @return
	 */
	@RequestMapping(value = "/order", method = RequestMethod.PUT)
	public @ResponseBody Object updateOrder(@RequestBody Order order) {
		return service.updateOrder(order);
	}

	/***
	 * 发货 必须参数：1,objectId or orderNo 2,express.expressCompany and expressNo
	 * @param order
	 * @return
	 */
	@RequestMapping(value = "/order/deliver", method = RequestMethod.POST)
	public @ResponseBody Object deliver(@RequestBody Order order) {
		Osslog.debug("cms.deliver：" + order);
		order.setStatus(DSConstants.ORDER_STATE_SHIPPED);
		Object o = service.changeState(order);
		return o;
	}
	
	/***
	 * 设置收货地址(拍卖用户)
	 * @param order
	 * @return
	 */
	@RequestMapping(value = "/order/address", method = RequestMethod.POST)
	public @ResponseBody Object setAddress(@RequestBody Order order) {
		Osslog.debug("cms.setAddress：" + order);
		return service.updateOrder(order);
	}
	

	/***
	 * 收货 必须参数：1,objectId or orderNo
	 * 
	 * @param order
	 * @return
	 */
	@RequestMapping(value = "/order/received", method = RequestMethod.POST)
	public @ResponseBody Object received(@RequestBody Order order) {
		Osslog.debug("cms.received：" + order);
		order.setStatus(DSConstants.ORDER_STATE_RECEIVED);
		order.setReceiverAt(new Date());
		Object o = service.changeState(order);
		return o;
	}

	/***
	 * //支付成功，改变订单状态 必须参数：objectId or orderNo
	 * 
	 * @param order
	 * @return
	 */
	@RequestMapping(value = "/order/paid", method = RequestMethod.POST)
	public @ResponseBody Object paid(@RequestBody Order order) {
		Osslog.debug("cms.paied：" + order);
		order.setStatus(DSConstants.ORDER_STATE_PAID);
		Object result = service.paySuccess(order);
		Osslog.debug("cms.paied.paySuccess" + result);
		String noticeUrl = PropertiesUtil.getInstance().getProperty("wxserviceurl") + "/notice/neworder";
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("orderNo", order.getOrderNo());
		String first="新订单通知";
		try {
			order = (Order) service.getByOrderNo(order.getOrderNo());
			Osslog.debug("cms.paied.result.getOrder" + order);
			String type = "";
			switch (order.getType()) {
				case 0:	
					type = "普通订单";
					break;
				case 1:
					type = "预定订单";
					break;
				case 2:
					type = "普通订单";
					break;
				case 3: 
					type = "秒杀订单";
					break;
				case 4: 
					type = "团购订单";
					break;
				case 5: 
					type = "拍卖订单";
					break;
				case 6: 
					type = "充值订单";
					break;
				case 7: 
					type = "新用户首单";
					break;
				case 8: 
					type = "拼团订单";
					break;
				case 9: 
					type = "砍价订单";
					break;
				default:break;
			}
			if(order.getType() == DSConstants.ORDER_TYPE_TEAM){
				//改变预订单状态
				String url = PropertiesUtil.getInstance().getProperty("teamurl")+"paysuccess?id="+order.getSpreadId()+"&orderNo="+order.getOrderNo();
				HttpUtils.sendGet(url);
				
				url = PropertiesUtil.getInstance().getProperty("teamurl")+"detail?teamInfoId="+order.getSpreadId();
				
				String teamJson = HttpUtils.sendGet(url);
				Osslog.debug("cms.paid success.teamJson: "+teamJson);
				JSONObject teamobjct = JSONObject.parseObject(teamJson);
				long limitCount =teamobjct.getLongValue("limitCount");
				long joinCount =teamobjct.getLongValue("joinCount");;
				//long preCount =teamobjct.getLongValue("preCount");;
				first=limitCount+"人团已拼了"+joinCount+"人。";
				
			}else if(order.getType() == DSConstants.ORDER_TYPE_CUT){
				String url = PropertiesUtil.getInstance().getProperty("cuturl")+"paysuccess?id="+order.getSpreadId();
				HttpUtils.sendGet(url);
			}
			
			param.put("first", first);
			param.put("orderType", type);
			param.put("totalFee", order.getTotalFee()+"");
			param.put("date", FormatDateTime.toShortTimeString3(order.getCreateAt()));
			param.put("userName", order.getExpress().getReceiver());
			param.put("mobile", order.getExpress().getMobile());
			param.put("remark", order.getTitle());
			/*YihuUserService service = new YihuUserService();
			UserPublishQuery query = new UserPublishQuery();
			query.setModel(0);
			List<String> openids = service.getOpenidsByQuery(query);*/
			try{
				param.put("openids", WexinMsgByGroupService.getCustomerService());	
			}
			catch(Exception e){
				e.printStackTrace();
				List<String> ids = new ArrayList<String>();
				ids.add("oimf-joPvA_sEwMtRSGq-md55-ts");
				ids.add("oimf-jtehtEB7jtBtvrC_fRaG12s");
				ids.add("oimf-jgdYFoN9qu_zfTfB0t67hYA");
				ids.add("oimf-jrjcbSAtz59WOc_bkzbJHWA");
				ids.add("oimf-jsEWodjb3gTcMCenfmqxTqY");
				ids.add("oimf-jryWaQb6hT1pKV7QzB5sn_o");				
				param.put("openids", ids);	
			}
			param.put("url", "/#/order/"+order.getOrderNo());
			String json = JSON.toJSONString(param);
			Osslog.debug("cms.notice.order：" + json);
			HttpUtils.sendPostJson(noticeUrl,json);
		} catch (Exception e) {
			Osslog.debug(e.getMessage());
			e.printStackTrace();
		}
		return result;
	}

	/***
	 * 修改价格
	 * 
	 * @param order
	 *            1，order.objecid,product.id,product.price
	 * @return
	 */
	@RequestMapping(value = "/order/changePrice", method = RequestMethod.POST)
	public @ResponseBody Object changePrice(@RequestBody Order order) {
		Osslog.debug("cms.changePrice：" + order);
		 Object o = service.changePrice(order);
		 ResultVO vo = (ResultVO)o;
		 if(vo.getResult()==DSConstants.RESULT_CODE_SUC){
			 String noticeUrl = PropertiesUtil.getInstance().getProperty("wxserviceurl") + "/notice/changeprice";
			 Map<String,Object> param = new HashMap<String,Object>();
			 param.put("orderNo", vo.getOrderNo());
			 param.put("oldPrice", vo.getOldPrice());
			 param.put("newPrice", vo.getNewPrice());
			 param.put("openid", vo.getOpenid());
			 param.put("url", "/#/order/"+vo.getOrderNo());
			 String json = JSON.toJSONString(param);
			Osslog.debug("cms.notice.changePrice：" + json);
			try {
				HttpUtils.sendPostJson(noticeUrl,json);
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 }
		 return o;
	}

	@RequestMapping(value = "/order/express/redis", method = RequestMethod.GET)
	public @ResponseBody Object getExpressFromRedis(String expressNo) {
		Osslog.debug("cms.getExpressFromRedis：" + expressNo);
		Object result = service.getExpressFromRedis(expressNo);
		Osslog.debug("cms.getExpressFromRedis.result：" + result);
		if (result != null && !result.toString().equals(""))
			return JSON.parse(result.toString());
		else
			return "";
	}

	@RequestMapping(value = "/order/express/redis", method = RequestMethod.POST)
	public @ResponseBody Object setExpressFromRedis(@RequestBody Express express) {
		Osslog.debug("cms.setExpressTo：" + express.getExpressInfo());
		return service.setExpressFromRedis(express.getExpressNo(), express.getExpressInfo());
	}

	/***
	 * 用户请求退款
	 * 
	 * @param order
	 *            id or orderNo
	 * @return
	 */
	@RequestMapping(value = "/order/user/refund", method = RequestMethod.POST)
	public @ResponseBody Object refundByUser(@RequestBody Order order) {
		Osslog.debug("cms.refundByUser：" + order);
		order.setStatus(DSConstants.ORDER_STATE_REFUND);
		//发送通知给后台管理员
		String reqUrl = PropertiesUtil.getInstance().getProperty("wxserviceurl") + "/refund/sys";
		Map<String,Object> param = new HashMap<String,Object>();
		try {
			Order o = (Order)service.getOrder(order);
			param.put("orderNo", o.getOrderNo());
			param.put("totalFee", o.getTotalFee());
			String reason= "用户申请退款";
			if(o.getType()==DSConstants.ORDER_TYPE_TEAM){
				reason = "拼团到期，人数未满退款";
			}
			param.put("reason", reason);
			param.put("openids", WexinMsgByGroupService.getCustomerService());	
			HttpUtils.sendPostJson(reqUrl, JSON.toJSONString(param));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return service.refund(order);
	}
	
	@RequestMapping(value = "/order/refund/test", method = RequestMethod.GET)
	public @ResponseBody Object retest(String orderNo){
		return userService.backRewards(orderNo);
	}

	/***
	 * 管理员同意退款
	 * 
	 * @param order
	 *            id or orderNo and openid
	 * @return
	 */
	@RequestMapping(value = "/order/sys/refund", method = RequestMethod.POST)
	public @ResponseBody Object refundBySys(@RequestBody Order order) {
		Osslog.debug("cms.refundBySys：" + order);	
		String refundUrl = PropertiesUtil.getInstance().getProperty("wxserviceurl") + "/wx/refund";
		Map<String, Object> param = new HashMap<String, Object>();
		Order o = (Order)service.getOrder(order);
		param.put("orderNo", order.getOrderNo());
		param.put("openid", order.getOpenid());
		order.setTotalFee(o.getTotalFee());
		ResultVO vo = new ResultVO();
		JSONObject jobject = null;
		try {
			String result = HttpUtils.sendPostJson(refundUrl, JSON.toJSONString(param));
			jobject = JSONObject.parseObject(result);
			if(jobject.getInteger("result")==1){
				order.setStatus(DSConstants.ORDER_STATE_REFUND_FAIL);
				ResultVO v = (ResultVO) service.changeState(order);
				if(v.getResult()==1){
					vo.setMessage("Successful refunds, failure to update the order state");
				}
				vo.setResult(DSConstants.RESULT_CODE_FAIL);
				vo.setMessage(jobject.getString("err_code_des"));
				//发送退款失败系统通知
				refundFailNotice(order);
				
			}else{
				ResponseVO resvo = userService.backRewards(order.getOrderNo());
				Osslog.debug("cms.refundrewads" + resvo);	
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			vo.setResult(DSConstants.RESULT_CODE_FAIL);
			vo.setMessage(jobject.getString("err_code_des"));;
		} 
		return vo;
	}

	/***
	 * 退款成功
	 * 
	 * @param order
	 *            id or orderNo
	 * @return
	 */
	@RequestMapping(value = "/order/refunded", method = RequestMethod.POST)
	public @ResponseBody Object refunded(@RequestBody Order order) {
		Osslog.debug("cms.refunded：" + order);
		order.setStatus(DSConstants.ORDER_STATE_REFUNDED);
		return service.refund(order);
	}

	/***
	 * 用户取消退款
	 * 
	 * @param order
	 *            id or orderNo
	 * @return
	 */
	@RequestMapping(value = "/order/user/cancelRefund", method = RequestMethod.POST)
	public @ResponseBody Object refundCancelByUser(@RequestBody Order order) {
		Osslog.debug("cms.refundCancelByUser：" + order);
		order.setStatus(0); // 标识用户
		return service.refundCancel(order);
	}

	/***
	 * 审核拒绝退款
	 * 
	 * @param order
	 *            id or orderNo
	 * @return
	 */
	@RequestMapping(value = "/order/sys/cancelRefund", method = RequestMethod.POST)
	public @ResponseBody Object refundCancelBySys(@RequestBody Order order) {
		Osslog.debug("cms.refundCancelBySys：" + order);
		order.setStatus(1); // 标识审核
		return service.refundCancel(order);
	}
	
	/***
	 * 获取优惠详情,购物车到订单
	 * 
	 * @param order
	 *            id or orderNo
	 * @return
	 */
	@RequestMapping(value = "/order/coupon/detail", method = RequestMethod.POST)
	public @ResponseBody Object getCouponDetailByArtwork(@RequestBody Order order) {
		Osslog.debug("cms.getCouponDetailByArtwork：" + order);
		if(order.getType()==DSConstants.ORDER_TYPE_FIRST){
			String result = "";
			try {
				StringBuffer sb = new StringBuffer();
				for(Product p:order.getProducts()){
					String id = p.getId();
					sb.append(id+",");
				}
				String url = PropertiesUtil.getInstance().getProperty("firsturl");
				url = url+"getFielddeails?ids="+sb.toString();
				result = HttpUtils.sendGet(url);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return result;
		}else
			return service.getCouponDetailByArtwork(order);
	}

}
